<template>
  <Dialog v-model="dialogVisible" title="导入学生信息" width="400">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      label-width="120px"
    >
      <el-form-item label="模板下载">
        <el-button type="primary" @click="importTemplate" plain>
          <Icon icon="ep:download" class="mr-5px" /> 点击下载
        </el-button>
      </el-form-item>
      <el-form-item label="文件上传">
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :before-upload="beforeUpload"
          :limit="1"
          accept=".xls,.xlsx"
          drag
        >
          <Icon icon="ep:upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>仅允许导入 xls、xlsx 格式文件。</span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="是否更新已有数据">
        <el-radio-group v-model="updateSupport">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="!currentFile">开始导入</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { StudentApi } from '@/api/ao/student'
import download from '@/utils/download'

/** 学生信息导入表单 */
defineOptions({ name: 'StudentImportForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const fileList = ref([])
const currentFile = ref()
const updateSupport = ref(false)

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  resetForm()
}

/** 提交表单 */
const submitForm = async () => {
  if (!currentFile.value) {
    message.error('请选择要导入的文件')
    return
  }

  try {
    formLoading.value = true

    // 构建表单数据
    const data = new FormData()
    data.append('file', currentFile.value)
    data.append('updateSupport', String(updateSupport.value))

    // 发起导入请求
    const result = await StudentApi.importStudent(data)

    console.log('导入结果：', result) // 添加调试日志

    // 构建结果消息
    let resultMessage = '导入完成！'
    if (result.createStudentCount > 0) {
      resultMessage += `成功创建 ${result.createStudentCount} 个学生。`
    }
    if (result.updateStudentCount > 0) {
      resultMessage += `成功更新 ${result.updateStudentCount} 个学生。`
    }
    if (result.failureStudentCount > 0) {
      resultMessage += `失败 ${result.failureStudentCount} 个学生。`
      if (result.failureStudentNames && result.failureStudentNames.length > 0) {
        resultMessage += `失败详情：${result.failureStudentNames.join(', ')}`
      }
    }

    if (result.failureStudentCount > 0) {
      message.warning(resultMessage)
    } else {
      message.success(resultMessage)
    }

    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('导入失败:', error)
    console.error('错误详情:', error.response?.data)

    let errorMessage = '导入失败'
    if (error.response?.data?.msg) {
      errorMessage += '：' + error.response.data.msg
    } else if (error.message) {
      errorMessage += '：' + error.message
    } else {
      errorMessage += '，请检查文件格式和数据'
    }

    message.error(errorMessage)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  // 重置表单数据
}

/** 下载模板 */
const importTemplate = async () => {
  try {
    const data = await StudentApi.importStudentTemplate()
    download.excel(data, '学生信息导入模板.xls')
  } catch {
    message.error('下载模板失败')
  }
}

/** 文件上传前的钩子 */
const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.ms-excel' || 
                  file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  if (!isExcel) {
    message.error('只能上传 Excel 文件!')
    return false
  }
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

/** 文件选择改变 */
const handleFileChange = (file) => {
  currentFile.value = file.raw
}

/** 文件移除 */
const handleFileRemove = () => {
  currentFile.value = null
}

/** 定义 emits */
const emit = defineEmits<{
  success: []
}>()

defineExpose({ open }) // 提供 open 方法
</script>
